package com.preserve.common.authentication.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.preserve.common.authentication.token.BaseUsernamePasswordToken;

public class BaseFormAuthenticationFilter extends FormAuthenticationFilter {

	// 创建 Token
	protected BaseUsernamePasswordToken createToken(ServletRequest request,
			ServletResponse response) {

		String username = getUsername(request);
		String password = getPassword(request);
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);

		return new BaseUsernamePasswordToken(username, password, rememberMe,
				host);
	}

	protected boolean executeLogin(ServletRequest request,
			ServletResponse response) throws Exception {
		BaseUsernamePasswordToken token = createToken(request, response);
		try {
			Subject subject = getSubject(request, response);
			subject.login(token);
			return onLoginSuccess(token, subject, request, response);
		} catch (AuthenticationException e) {
			return onLoginFailure(token, e, request, response);
		}
	}

}
